// 前端菜单服务
import { useAuthStore } from '@/stores/auth';

// 获取用户菜单
export const getUserMenuService = async () => {
  const authStore = useAuthStore();
  
  try {
    // 确保用户已登录
    if (!authStore.token) {
      console.warn('User not logged in, returning default menus');
      return getDefaultMenus();
    }
    
    const response = await fetch('/api/admin/menus/user', {
      headers: {
        'Authorization': `Bearer ${authStore.token}`,
        'Content-Type': 'application/json'
      }
    });
    
    if (response.ok) {
      const menus = await response.json();
      // 确保返回的数据是正确的格式
      if (Array.isArray(menus)) {
        return menus; // 后端已返回构建好的菜单树，无需再次构建
      } else {
        console.warn('Invalid menu data format received, using defaults');
        return getDefaultMenus();
      }
    } else {
      console.error('Failed to load user menus:', response.status, response.statusText);
      // 如果API调用失败，返回默认菜单结构
      return getDefaultMenus();
    }
  } catch (error) {
    console.error('Error loading user menus:', error);
    // 如果发生错误，返回默认菜单结构
    return getDefaultMenus();
  }
};

// 构建菜单树结构
export const buildMenuTree = (menuList) => {
  if (!menuList || menuList.length === 0) {
    return [];
  }
  
  const map = {};
  const roots = [];
  
  // 创建映射
  menuList.forEach(menu => {
    menu.children = [];
    map[menu.menuId] = menu;
  });
  
  // 构建树
  menuList.forEach(menu => {
    if (menu.parentId) {
      const parent = map[menu.parentId];
      if (parent) {
        parent.children.push(menu);
      } else {
        roots.push(menu);
      }
    } else {
      roots.push(menu);
    }
  });
  
  return roots;
};

// 默认菜单结构（当API不可用时使用）
export const getDefaultMenus = () => {
  return [
    // 用户权限管理分类
    {
      menuId: 'user_permission_mgmt',
      menuName: '用户权限管理',
      menuIcon: 'users',
      menuUrl: '#',  // 分类不直接导航
      parentId: null,
      children: [
        {
          menuId: 'user_management',
          menuName: '用户管理',
          menuIcon: 'users',
          menuUrl: '/admin/users',
          parentId: 'user_permission_mgmt',
          children: []
        },
        {
          menuId: 'role_management',
          menuName: '角色管理',
          menuIcon: 'roles',
          menuUrl: '/admin/roles',
          parentId: 'user_permission_mgmt',
          children: []
        },
        {
          menuId: 'permission_management',
          menuName: '权限管理',
          menuIcon: 'permission',
          menuUrl: '/admin/permissions',
          parentId: 'user_permission_mgmt',
          children: []
        },
        {
          menuId: 'menu_management',
          menuName: '菜单管理',
          menuIcon: 'menu',
          menuUrl: '/admin/menus',
          parentId: 'user_permission_mgmt',
          children: []
        },
        {
          menuId: 'user_role_management',
          menuName: '用户角色管理',
          menuIcon: 'user-roles',
          menuUrl: '/admin/user-roles',
          parentId: 'user_permission_mgmt',
          children: []
        }
      ]
    },
    // 课程排课管理分类
    {
      menuId: 'course_schedule_mgmt',
      menuName: '课程排课管理',
      menuIcon: 'course',
      menuUrl: '#',  // 分类不直接导航
      parentId: null,
      children: [
        {
          menuId: 'course_management',
          menuName: '开设课程管理',
          menuIcon: 'course',
          menuUrl: '/admin/courses',
          parentId: 'course_schedule_mgmt',
          children: []
        },
        {
          menuId: 'schedule_management',
          menuName: '排课管理',
          menuIcon: 'schedule',
          menuUrl: '/admin/schedules',
          parentId: 'course_schedule_mgmt',
          children: []
        }
      ]
    },
    // 业务管理分类
    {
      menuId: 'business_mgmt',
      menuName: '业务管理',
      menuIcon: 'business',
      menuUrl: '#',  // 分类不直接导航
      parentId: null,
      children: [
        {
          menuId: 'booking_management',
          menuName: '预约管理',
          menuIcon: 'booking',
          menuUrl: '/admin/bookings',
          parentId: 'business_mgmt',
          children: []
        },
        {
          menuId: 'order_management',
          menuName: '订单管理',
          menuIcon: 'order',
          menuUrl: '/admin/orders',
          parentId: 'business_mgmt',
          children: []
        },
        {
          menuId: 'youbi_management',
          menuName: '优币管理',
          menuIcon: 'youbi',
          menuUrl: '/admin/youbi',
          parentId: 'business_mgmt',
          children: []
        },
        {
          menuId: 'message_management',
          menuName: '消息管理',
          menuIcon: 'message',
          menuUrl: '/admin/messages',
          parentId: 'business_mgmt',
          children: []
        }
      ]
    },
    // 系统管理分类
    {
      menuId: 'system_mgmt',
      menuName: '系统管理',
      menuIcon: 'settings',
      menuUrl: '#',  // 分类不直接导航
      parentId: null,
      children: [
        {
          menuId: 'system_settings',
          menuName: '系统设置',
          menuIcon: 'settings',
          menuUrl: '/admin/settings',
          parentId: 'system_mgmt',
          children: []
        },
        {
          menuId: 'system_monitor',
          menuName: '系统监控',
          menuIcon: 'monitor',
          menuUrl: '/admin/monitor',
          parentId: 'system_mgmt',
          children: []
        }
      ]
    }
  ];
};

// 检查用户权限
export const checkPermission = async (permissionCode) => {
  const authStore = useAuthStore();
  
  try {
    // 这里可以调用API检查用户是否有特定权限
    // 示例实现：
    const response = await fetch(`/api/admin/permissions/check?code=${permissionCode}`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`,
        'Content-Type': 'application/json'
      }
    });
    
    if (response.ok) {
      const result = await response.json();
      return result.hasPermission || false;
    } else {
      return false;
    }
  } catch (error) {
    console.error('Error checking permission:', error);
    return false;
  }
};

// 将菜单转换为Element Plus的el-menu格式
export const formatMenuForDisplay = (menuTree) => {
  return menuTree.map(menu => {
    const formattedMenu = {
      index: menu.menuUrl,
      title: menu.menuName,
      icon: menu.menuIcon,
      url: menu.menuUrl
    };
    
    if (menu.children && menu.children.length > 0) {
      formattedMenu.children = formatMenuForDisplay(menu.children);
    }
    
    return formattedMenu;
  });
};